﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace ExcelFileQueryTool
{
    public partial class frmClientFileDetail : Form
    {
        public frmClientFileDetail()
        {
            InitializeComponent();
        }

        private void FindClientFile(string clientName)
        {
            string[] files = null;

            if (string.IsNullOrEmpty(clientName) == false)
            {
                files = Directory.GetFiles(AppConfig.SourceFolder, String.Format("[对数表]*{0}*.xlsx", clientName), SearchOption.AllDirectories);
                var filesWithSimilarity = new List<KeyValuePair<string, decimal>>();

                if (files == null || files.Length == 0)
                {
                    files = Directory.GetFiles(AppConfig.SourceFolder, AppConfig.FilePattern, SearchOption.AllDirectories);

                    foreach (var f in files)
                    {
                        var sv = GetFileNameSimilarity(f, clientName);
                        if (sv >= 0.5m)
                            filesWithSimilarity.Add(new KeyValuePair<string, decimal>(f, sv));
                    }

                    files = filesWithSimilarity.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray();
                }
                else if (files.Length > 1)
                {
                    foreach (var f in files)
                    {
                        var sv = GetFileNameSimilarity(f, clientName);
                        filesWithSimilarity.Add(new KeyValuePair<string, decimal>(f, sv));
                    }

                    files = filesWithSimilarity.OrderByDescending(x => x.Value).Select(x => x.Key).ToArray();
                }
            }

            //if (files != null)
            //{
            //    files = files.Where(x => AppConfig.ExcludeFileNames.All(y => x.EndsWith(y) == false)).ToArray();
            //}

            ShowFileSelectionGrid(files);
        }

        private static decimal GetFileNameSimilarity(string f, string clientName)
        {
            var fn = ClientFileService.GetClientNameFromFile(Path.GetFileNameWithoutExtension(f).Replace("[对数表]", string.Empty));
            return LevenshteinDistance.GetSimilarity(fn, clientName);
        }

        private void ShowFileSelectionGrid(IEnumerable<string> files)
        {
            DataGridView dgv = null;
            const string dgv_name = "dgvFiles";

            if (this.Controls.ContainsKey(dgv_name))
            {
                dgv = (DataGridView)this.Controls[dgv_name];
                dgv.Rows.Clear();
            }
            else
            {
                dgv = new DataGridView();
                dgv.Name = dgv_name;
                dgv.Location = new Point(10, 40);
                dgv.Width = this.ClientRectangle.Width - 30;
                dgv.Height = 150;
                dgv.BackgroundColor = Color.AliceBlue;
                dgv.AutoGenerateColumns = false;
                dgv.AllowUserToAddRows = false;
                dgv.AllowUserToDeleteRows = false;
                dgv.AllowUserToOrderColumns = false;
                dgv.AllowUserToResizeRows = false;
                dgv.MultiSelect = false;
                dgv.EditMode = DataGridViewEditMode.EditProgrammatically;
                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                dgv.Columns.Add("file", "文件名");
                dgv.Columns.Add(new DataGridViewButtonColumn { Text = "打开", UseColumnTextForButtonValue = true });
                dgv.Columns.Add(new DataGridViewButtonColumn { Text = "复制", UseColumnTextForButtonValue = true });

                dgv.CellClick += (sender, e) =>
                {
                    if (e.RowIndex < 0)
                        return;

                    var grid = (DataGridView)sender;

                    switch (e.ColumnIndex)
                    {
                        case 1: // 打开
                            {
                                var selectedFile = grid[0, e.RowIndex].ToolTipText;
                                using (Process.Start(selectedFile)) { }
                                break;
                            }
                        case 2: // 复制
                            {
                                using (SaveFileDialog saveDiag = new SaveFileDialog())
                                {
                                    saveDiag.Filter = AppConfig.ClientFileChooseFilter;

                                    if (saveDiag.ShowDialog() == DialogResult.OK)
                                    {
                                        var selectedFile = grid[0, e.RowIndex].ToolTipText;
                                        File.Copy(selectedFile, saveDiag.FileName, true);
                                    }
                                }
                                break;
                            }
                        default:
                            break;
                    }
                };

                dgv.KeyDown += (sender, e) =>
                {
                    if (e.KeyCode != Keys.Enter)
                        return;

                    e.Handled = true; // 避免自动换行
                    var grid = (DataGridView)sender;

                    if (grid.SelectedRows == null)
                        return;

                    var rowIndex = grid.SelectedRows[0].Index;

                    var selectedFile = grid.Rows[rowIndex].Cells[0].ToolTipText;
                    using (Process.Start(selectedFile)) { }
                };

                this.Height += (dgv.Height);
                this.Controls.Add(dgv);
            }

            if (files == null || files.Count() == 0)
                return;

            foreach (var f in files)
            {
                var row = new DataGridViewRow();
                row.Cells.Add(new DataGridViewTextBoxCell
                {
                    Value = ClientFileService.GetClientNameFromFile(f),
                    ToolTipText = f
                });

                dgv.Rows.Add(row);
            }

            dgv.Select(); // for auto open function
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var name = txtClientName.Text.Trim();

            FindClientFile(name);
        }

        private void txtClientName_Click(object sender, EventArgs e)
        {
            this.txtClientName.SelectAll();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F3)
            {
                txtClientName.SelectAll();
                txtClientName.Focus();
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}
